<?php

namespace app\api\controller\user;

use app\common\controller\Api;
use think\Db;
use think\Config;
use app\common\controller\Commission;
use app\admin\controller\Zfb;

//合伙人用户
class PartnerUser extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 储值管理
     * @ApiMethod (GET)
     * @path api/user/partner_user/stored
     */
    public function stored()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);

        $user = db('user')->field('storage_balance,is_card_pay')->where(['id'=>$user_id])->find();
        $storedTotal = db('card_pay')->where(['user_id'=>$user_id,'ispay'=>1,'user_del'=>'0'])->sum('price');
        $user['stored_total'] = $storedTotal;

        $log = db('card_pay')
            ->field('pay_type,price,addtime')
            ->where(['user_id'=>$user_id,'ispay'=>1,'user_del'=>'0'])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        if (!empty($log)) {
            $log = $log->toArray();
            foreach ($log['data'] AS $key => $value) {
                $log['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
            }
        }

        $this->success('请求成功',[
            'user_info'=>$user,
            'list'=>$log
        ]);
    }


    /**
     * 推广中心/空间管理
     * @ApiMethod (GET)
     * @path api/user/partner_user/promotionStore
     */
    public function promotionStore()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);

        $user = db('user')->field('promotion_money')->where(['id'=>$user_id])->find();
        //推广总金额
        $promotionTotal = db('promition_log')->where(['promotion_id'=>$user_id,'type'=>1,'user_del'=>'0'])->where('promotion_type2','in',[1,2])->sum('price');
        //推广提现中金额
        $promotionPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>1,'type'=>2,'user_del'=>'0'])->sum('price');
        //推广不可提现金额
        $promotionNoPrice = db('order_goods_store')->where(['isfa'=>0,'promotion_id'=>$user_id])->where('authen','in',[0,3])->sum('promotion_price_pt');
        //推广已提现金额
        $promotionAlreadyPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>2,'type'=>2,'user_del'=>'0'])->sum('price');



        $user['promotion_total'] = $promotionTotal;
        $user['promotion_price'] = $promotionPrice;
        $user['promotion_no_price'] = $promotionNoPrice;
        $user['promotion_already_price'] = $promotionAlreadyPrice;


        $log = db('promition_log')
            ->field('id,type,price,addtime,promotion_type2,promotion_id2')
            ->where(['promotion_id'=>$user_id,'user_del'=>'0'])
            ->where('promotion_type2','in',[1,2])

            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $log = $log->toArray();
        foreach ($log['data'] AS $key => $value) {
            $msg = "推广";
            if ($value['promotion_type2'] == 1) {
                //中心
                $name = db('store')->where('id',$value['promotion_id2'])->value('store_name');
                $msg .= "中心：".$name;
            } elseif ($value['promotion_type2'] == 2) {
                //空间
                $name = db('store')->where('id',$value['promotion_id2'])->value('store_name');
                $msg .= "空间：".$name;
            } else {
                //合伙人
                $name = db('user')->where('id',$value['promotion_id2'])->value('username');
                $msg .= "合伙人：".$name;
            }
            $log['data'][$key]['title'] = $msg;
            $log['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
            
        }
        $this->success('请求成功',[
            'user_info'=>$user,
            'list'=>$log
        ]);
    }


    /**
     * 推广合伙人管理
     * @ApiMethod (GET)
     * @path api/user/partner_user/promotioPartner
     */
    public function promotioPartner()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);

        $user = db('user')->field('promotion_balance')->where(['id'=>$user_id])->find();

        //推广总金额
        $promotionTotal = db('promition_log')->where(['promotion_id'=>$user_id,'type'=>1,'promotion_type2'=>3,'user_del'=>'0'])->sum('price');
        //推广提现中金额
        $promotionPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>1,'type'=>3,'user_del'=>'0'])->sum('price');
        //推广已提现金额
        $promotionAlreadyPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>2,'type'=>3,'user_del'=>'0'])->sum('price');



        $user['promotion_total'] = $promotionTotal;
        $user['promotion_price'] = $promotionPrice;
        $user['promotion_already_price'] = $promotionAlreadyPrice;


        $log = db('promition_log')
            ->field('id,type,price,addtime,promotion_type2,promotion_id2')
            ->where(['promotion_type'=>3,'promotion_id'=>$user_id,'promotion_type2'=>3,'user_del'=>'0'])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $log = $log->toArray();
        foreach ($log['data'] AS $key => $value) {
            $msg = "推广";
            if ($value['promotion_type2'] == 1) {
                //中心
                $name = db('store')->where('id',$value['promotion_id2'])->value('store_name');
                $msg .= "中心：".$name;
            } elseif ($value['promotion_type2'] == 2) {
                //空间
                $name = db('store')->where('id',$value['promotion_id2'])->value('store_name');
                $msg .= "空间：".$name;
            } else {
                //合伙人
                $name = db('user')->where('id',$value['promotion_id2'])->value('username');
                $msg .= "合伙人：".$name;
            }
            $log['data'][$key]['title'] = $msg;
            $log['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }

        $this->success('请求成功',[
            'user_info'=>$user,
            'list'=>$log
        ]);
    }

    /**
     * 分红管理
     * @ApiMethod (GET)
     * @path api/user/partner_user/bons
     */
    public function bons()
    {
        $user_id = $this->auth->id;
        $page = $this->request->param('page',1);
        $user = db('user')->field('bonus_balance')->where(['id'=>$user_id])->find();

        //分红总金额
        $bonsTotal = db('order_bonus')->where(['promotion_id'=>$user_id,'authen'=>2,'user_del'=>'0'])->sum('price');
        //分红提现中金额
        $bonsPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>1,'type'=>6,'user_del'=>'0'])->sum('price');
        //分红已提现金额
        $bonsAlreadyPrice = db('withdraw')->where(['user_id'=>$user_id,'status'=>2,'type'=>6,'user_del'=>'0'])->sum('price');

        $user['bons_otal'] = $bonsTotal;
        $user['bons_price'] = $bonsPrice;
        $user['bons_already_price'] = $bonsAlreadyPrice;

        $log = db('order_bonus')
            ->where(['promotion_id'=>$user_id,'authen'=>2,'user_del'=>'0'])
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);
        if (!empty($log)) {
            $log = $log->toArray();
            foreach ($log['data'] AS $key => $value) {
                $log['data'][$key]['kou_rate'] = 0;
                if (trim($value['rate']) !== 100) {
                    $log['data'][$key]['kou_rate'] = 100-$value['rate'];
                }
                $log['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
                $log['data'][$key]['authen_time'] = date('Y-m-d H:i:s',$value['authen_time']);
                $log['data'][$key]['start_time'] = date('Y-m-d H:i:s',$value['start_time']);
                $log['data'][$key]['end_time'] = date('Y-m-d H:i:s',$value['end_time']);
            }
        }
        $this->success('请求成功',[
            'user_info'=>$user,
            'list'=>$log
        ]);
    }

    /**
     * 合伙人充值
     * @ApiMethod (POST)
     * @path api/user/partner_user/recharge
     */
    public function recharge()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;
            $storeId = $this->auth->store_id;
            $price = $this->request->post('price',0);
            $price = trim($price);
            $isFirst = 2;//默认不是首冲
            if ($price <= 0) {
                $this->error('充值金额错误');
            }
            $user = db('user')->where(['id'=>$userId])->find();
            if ($user['is_card_pay'] == 0) {
                //首冲限制充值金额
                $firstPrice = db('config')->where(['name'=>'partner_price_first','group'=>'basic'])->value('value');
                if ($price !== $firstPrice) {
                    $this->error('首次请充值¥'.$firstPrice);
                }
                db('user')->where('id',$userId)->update([
                    'is_card_pay'=>1,
                    'card_pay_time'=>time(),
                    'first_storage_balance'=>$price
                ]);
                $isFirst = 1;
            }
            $ordernum = generateOrderNumber();
            //添加充值记录
            db('card_pay')->insert([
                'type'=>3,
                'store_id'=>$storeId,
                'user_id'=>$userId,
                'price'=>$price,
                'pay_type'=>1,
                'ordernum'=>$ordernum,
                'is_first'=>$isFirst,
                'ispay'=>0,
                'addtime'=>time()
            ]);

            /********回调start********/
            //更新余额
            $user = db('user')->where('id',$userId)->lock(true)->find();
            db('user')->where('id',$userId)->setInc('storage_balance',$price);

            //增加资金变动明细
            db('card_log')->insert([
                'type'=>3,
                'user_id'=>$userId,
                'price'=>$price,
                'new_price'=>$user['storage_balance']+$price,
                'pay_type'=>1,
                'ordernum'=>generateOrderNumber(),
                'is_first'=>2,
                'ispay'=>1,
                'addtime'=>time(),
                'user_del'=>0
            ]);

            db("card_pay")->where('ordernum',$ordernum)->update([
                'ispay'=>1,
            ]);
            /********回调end********/


            //生成支付参数，支付回调中加钱
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('已生成充值单');
    }


    /**
     * 合伙人充值
     * @ApiMethod (POST)
     * @path api/user/partner_user/recharge
     */
    public function recharge1()
    {
        Db::startTrans();
        try {
            $userId = $this->auth->id;
            $storeId = $this->auth->store_id;
            $price = $this->request->post('price',0);
            $price = trim($price);
            $isFirst = 2;//默认不是首冲
            if ($price <= 0) {
                $this->error('充值金额错误');
            }
            $user = db('user')->where(['id'=>$userId])->find();
            if ($user['is_card_pay'] == 0) {
                //首冲限制充值金额
                $firstPrice = db('config')->where(['name'=>'partner_price_first','group'=>'basic'])->value('value');
                if ($price !== $firstPrice) {
                    $this->error('首次请充值¥'.$firstPrice);
                }
                db('user')->where('id',$userId)->update([
                    'is_card_pay'=>1,
                    'card_pay_time'=>time(),
                    'first_storage_balance'=>$price
                ]);
                $isFirst = 1;
            }
            $ordernum = generateOrderNumber();
            //添加充值记录
            db('card_pay')->insert([
                'type'=>3,
                'store_id'=>$storeId,
                'user_id'=>$userId,
                'price'=>$price,
                'pay_type'=>1,
                'ordernum'=>$ordernum,
                'is_first'=>$isFirst,
                'ispay'=>0,
                'addtime'=>time()
            ]);
            
            /*****生成拉起在线支付的参数******/
            $Zfb = new Zfb;
            $orderinfo['price']=0.01;
            $orderinfo['order_no']=$ordernum;
            $orderinfo['remark']=$user['username'].'合伙人充值';
            $orderinfo['store_id']=$storeId;
            $orderinfo['notify']="/fQlTgiAVKu.php/zfb/chongZhiNotify";
            // var_dump($orderno);
            $resq = $Zfb->navpay($orderinfo);

            if($resq['error']==0) {
                $json=json_encode($resq['res']); 
                $array = json_decode($json, true);
                $qrcode=$this->create_ewm($array['qr_code']);
                if($qrcode==1) {
                    Db::rollback();
                    $this->error('请重试');
                } else {
                    Db::commit();
                    $this->success('充值成功',[
                        'qrcode'=>protocol_name() . '://' . $_SERVER['SERVER_NAME'].$qrcode,
                        'orderno'=>$ordernum
                    ]);
                }
            } else {
                Db::rollback();
                $this->error('请求失败');
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
    }

    //二维码
    public function create_ewm($value){
        //生成二维码
        $matrixPointSize=24;
        vendor('phpqrcode');//引入类库
        $errorCorrectionLevel = 'L';  //容错级别
        // 判断是否有这个文件夹  没有的话就创建一个
        if(!is_dir("uploads/qecode")){
            // 创建文件加
            mkdir("uploads/qecode");
        }
        //设置二维码文件名
        $name=generateOrderNumber();
        $filename = "uploads/qecode/".$name.".png";
        if(file_exists("./".$filename)){
            // return '/'.$filename;
            return 1;
        }
        //生成二维码
        \QRcode::png($value,$filename,$errorCorrectionLevel,$matrixPointSize, 2);

        return '/'.$filename;
    }


    /**
     * 合伙人提货订单列表
     * @ApiMethod (GET)
     * @path api/user/partner_user/orderList
     */
    public function orderList()
    {
        $user_id = $this->auth->id;
        $store_id = $this->auth->store_id;
        $page = $this->request->param('page',1);
        //2待自提  4已完成
        $orderStatus = $this->request->param('order_status',2);
        $where = [
            'o.user_id'=>$user_id,
            'o.order_type'=>'3',
            'o.store_id'=>$store_id
        ];
        if (!empty($orderStatus)) {
            $where['order_status'] = $orderStatus;
        }
        $order = db('order')
            ->field('o.id,o.price,o.order_no,o.addtime,s.store_name,s.avatar,o.user_id')
            ->alias('o')
            ->join("store s","o.store_id = s.id","LEFT")
            ->where($where)
            ->order('addtime DESC')
            ->paginate(10, false, ['page' => $page]);

        $order = $order->toArray();


        foreach ($order['data'] AS $key => $value) {
            $order['data'][$key]['addtime'] = date('Y-m-d H:i:s',$value['addtime']);
        }
        
        $order['data'] = addWebSiteUrl($order['data'],['avatar']);
        $this->success('请求成功',$order);
    }

    /**
     * 合伙人提货订单详情
     * @ApiMethod (GET)
     * @path api/user/partner_user/orderDetail
     */
    public function orderDetail()
    {
        $userId = $this->auth->id;
        $storeId = $this->auth->store_id;
        $orderId = $this->request->param('order_id',0);
        $order = db('order')->field('id,order_no,order_status,name,tel,price,addtime,order_qr_time')->where(['id'=>$orderId,'user_id'=>$userId])->find();
        if (empty($order)) {
            $this->error('订单不存在');
        }
        $order['addtime'] = date('Y-m-d H:i:s',$order['addtime']);
        $order['order_qr_time'] = date('Y-m-d H:i:s',$order['order_qr_time']);
        $store = db('store')->field('tel,store_name,business_start_time,business_end_time,province,city,area,address')->where('id',$storeId)->find();
        $province = db('area')->where('id',$store['province'])->value('name');
        $city = db('area')->where('id',$store['city'])->value('name');
        $area = db('area')->where('id',$store['area'])->value('name');
        $store['province_name'] = $province;
        $store['city_name'] = $city;
        $store['area_name'] = $area;
        $orderGoods = db('order_goods')->field('goods_name,price,spec_name,goods_pic,num')->where('order_id',$orderId)->select();
        $orderGoods = addWebSiteUrl($orderGoods,['goods_pic']);
        $order['order_goods'] = $orderGoods;

        $this->success('请求成功',[
            'store'=>$store,
            'order'=>$order
        ]);
    }

    /**
     * 合伙人提货订单核销码
     * @path api/user/partner_user/orderCode
     */
    public function orderCode()
    {
        $orderId = $this->request->param('order_id',0);
        $orderInfo = db('order')->field('id,ti_code')->where('id',$orderId)->find();
        if (empty($orderInfo)) {
            $this->error('订单不存在');
        }
        $this->success('请求成功',$orderInfo);
    }

    /**
     * 合伙人提货订单确认收货
     * @path api/user/partner_user/confirmOrder
     */
    public function confirmOrder()
    {
        Db::startTrans();
        try{
            $userId = $this->auth->id;//后期从token或者公共存储区域读取
            $storeId = $this->auth->store_id;
            $orderId = $this->request->post('order_id',0);

            $orderInfo = db('order')->where(['user_id'=>$userId,'id'=>$orderId])->find();
            $store = db('store')->where(['id'=>$storeId])->find();
            if (empty($orderInfo)) {
                Db::rollback();
                $this->error('订单不存在');
            }
            if (in_array($orderInfo['order_status'],[0,4,5])) {
                Db::rollback();
                $this->error('订单状态错误');
            }
            /**********更新订单状态**********/
            db('order')->where(['user_id'=>$userId,'id'=>$orderId])->update([
                'order_status'=>4,
                'order_qr_time'=>time()
            ]);

            //更新商品销量
            $orderGoods = db('order_goods')->where('order_id',$orderId)->select();
            foreach ($orderGoods AS $key => $value) {
                db('goods')->where('id',$value['goods_id'])->setInc('salecount',$value['num']);
            }

            //1=采购发放,2=核销发送
            $promotionRule = db('promotion_rule')->limit(0,1)->value('promotion_status');

            //判断发放佣金的模式，核销模式才发
            if ($promotionRule == 2) {
                //业务佣金发放
                $commissionServices = new Commission();
                $yeWu = $commissionServices->yeWuPrice($orderId,$storeId);
                if ($yeWu == false) {
                    Db::rollback();
                    $this->error('业务员佣金发放失败');
                }

                //推广佣金
                $tuiGuang = $commissionServices->promotionPrice($orderId,$storeId);
                if ($tuiGuang == false) {
                    Db::rollback();
                    $this->error('推广佣金发放失败');
                }

                //更新order_goods_store发放状态
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'isfa' => 1,
                    'fa_time'=>time(),
                    'successtime'=>time(),
                ]);
            }
            if ($promotionRule == 1) {
                //业务佣金发放
                $commissionServices = new Commission();
                $yeWu = $commissionServices->yeWuPrice($orderId,$storeId);
                if ($yeWu == false) {
                    Db::rollback();
                    $this->error('业务员佣金发放失败');
                }

                //推广佣金
                $tuiGuang = $commissionServices->promotionPrice_cai($orderId,$storeId);
                if ($tuiGuang == false) {
                    Db::rollback();
                    $this->error('推广佣金发放失败');
                }

                //更新order_goods_store发放状态
                // db('order_goods_store')->where(['order_id'=>$orderId])->update([
                //     'isfa' => 1,
                //     'fa_time'=>time(),
                //     'successtime'=>time(),
                // ]);
                 //更新order_goods_store发放状态
                db('order_goods_store')->where(['order_id'=>$orderId])->update([
                    'successtime'=>time(),
                ]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('已确认收货');
    }

}
